from fastapi import APIRouter, Depends, HTTPException
from dependencies import get_request_ip_key, get_current_active_user, get_user
from models import ZhanUser, ChatSession, ChatMessage

from services.chat.chat_gpt_application import ChatService, OpenAiService, ChatApplicationService
from schemas.chat import ChatMessagePydantic, ChatApplicationPydantic, ChatApplicationMessagePydantic, \
    ChatSessionPydanticList, ChatSessionMessagePydantic, ChatMessagePydanticList

router = APIRouter(
    prefix="/chat_application",
    tags=["Chat Application"],
    # dependencies=[Depends(get_token_header)],
    responses={404: {"description": "Not found"}},
)


@router.post("/application")
async def chat_application(chat_application_item: ChatApplicationPydantic,
                           current_user: ZhanUser = Depends(get_current_active_user)):
    chat_application_item.user_id = current_user
    data = chat_application_item.dict()
    await ChatApplicationService.save_application(data)
    return {"data": "success"}


@router.post("/application/chat", dependencies=[Depends(get_request_ip_key)])
async def chat_application_message(chat_application_item: ChatApplicationMessagePydantic):
    message = []
    data = chat_application_item.dict()
    if data["application_id"]:
        instruct = await ChatApplicationService.get_application_info(data["application_id"])
        message.append({
            "role": "user",
            "content": instruct.instruct
        })
    elif data["instruct"]:
        message.append({
            "role": "user",
            "content": data["instruct"]
        })
    else:
        raise HTTPException(status_code=400, detail="missing parameter")
    message.append({
        "role": "user",
        "content": data["examples"]
    })
    message_info, completion = await OpenAiService.send_message(message)
    return {"message": message_info}


#
# @router.get("/application")
# async def chat_application():
#     c = await ChatApplicationPydanticList.from_queryset(ChatApplication.all())
#     return {"data": c.dict()["__root__"]}


@router.get("/application/search")
async def application_search(value: str = None, user: ZhanUser = Depends(get_user)):
    return await ChatApplicationService.search_application(value, user)


# 查询用户创建的应用 和 收藏应用
@router.get("/application/search/my")
async def application_search(value: str = None, user: ZhanUser = Depends(get_current_active_user)):
    return await ChatApplicationService.search_my_application(value, user)


@router.post("/chat", dependencies=[Depends(get_request_ip_key)])
async def chat(chat_message: ChatMessagePydantic):
    message_info, completion = await OpenAiService.send_message(chat_message.dict()["message_list"])
    return {"message": message_info}


@router.post("/user_chat", dependencies=[Depends(get_request_ip_key)])
async def user_chat(chat_message: ChatMessagePydantic, current_user: ZhanUser = Depends(get_current_active_user)):
    # 检测用户ip，保证每天的免费条数，如果存在私钥，则判断私钥的剩余使用次数
    chat_session, new = await ChatService.get_session(chat_message.chat_id, chat_message.message, current_user)
    message = await ChatService.compose(chat_message, chat_session)
    message_info, completion = await OpenAiService.send_message(message, chat_session)
    if new:
        await ChatService.save_session(completion, chat_session)
    return {"message": message_info}


@router.get("/user_chat/session_list")
async def user_chat_message_list(current_user: ZhanUser = Depends(get_current_active_user)):
    session_list = ChatSession.filter(user_id=current_user)
    session_list = await ChatSessionPydanticList.from_queryset(session_list)
    return session_list.dict()["__root__"]


@router.get("/user_chat/message_list")
async def user_chat_message_list(chat_session: ChatSessionMessagePydantic,
                                 current_user: ZhanUser = Depends(get_current_active_user)):
    message_list = ChatMessage.filter(owner_user=current_user, owner_chat_id=chat_session.session_id)
    message_list = await ChatMessagePydanticList.from_queryset(message_list)
    return message_list.dict()["__root__"]
